package controllers

import (
	"encoding/json"
	"ssims/models"
	"ssims/pkg/app"
	"ssims/pkg/e"
	"ssims/services"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func GetSc(c *gin.Context) {
	page := -1
	if arg := c.Query("page"); arg != "" {
		page = com.StrTo(arg).MustInt()
	}
	limit := -1
	if arg := c.Query("limit"); arg != "" {
		limit = com.StrTo(arg).MustInt()
	}
	searchNo := ""
	if arg := c.Query("searchNo"); arg != "" {
		searchNo = arg
	}
	supplierParam := map[string]interface{}{
		"page":     page,
		"limit":    limit,
		"searchNo": searchNo,
	}
	err, info, total := services.GetAllSc(supplierParam)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total}, "查询成功")
}

func DelSc(c *gin.Context) {
	name := ""
	if arg := c.Query("student_name"); arg != "" {
		name = arg
	}
	if name == "" {
		app.INFO(c, 30001, "参数错误")
		return
	}
	err := services.DelSc(name)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "删除成功")
}

func UpdateSc(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	if m["StudentName"] == "" {
		app.INFO(c, 30000, "参数非法")
		return
	}
	studentname := m["StudentName"]
	coursename := m["CourseName"]
	scgrade := com.StrTo(m["ScGrade"]).MustInt()
	err := services.UpdateSc(models.Sc{StudentName: studentname, CourseName: coursename, ScGrade: scgrade, Isdel: false, UpdateTime: time.Now()})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "更新成功")
}

func AddSc(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	studentname := m["StudentName"]
	coursename := m["CourseName"]
	scgrade := com.StrTo(m["ScGrade"]).MustInt()
	err := services.AddSc(models.Sc{StudentName: studentname, CourseName: coursename, ScGrade: scgrade, Isdel: false, UpdateTime: time.Now()})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "添加成功")
}

func GetNumber(c *gin.Context) {
	page := -1
	if arg := c.Query("page"); arg != "" {
		page = com.StrTo(arg).MustInt()
	}
	limit := -1
	if arg := c.Query("limit"); arg != "" {
		limit = com.StrTo(arg).MustInt()
	}
	supplierParam := map[string]interface{}{
		"page":     page,
		"limit":    limit,
	}
	err, info, total := services.GetNumber(supplierParam)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total}, "查询成功")
}
